package com.example.nequimessage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import org.json.JSONObject;

public class HttpUtils {

    public HttpUtils(){

    }

    public static String getJsonContent(String url_path) {
        try{
            URL url = new URL(url_path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            int code = connection.getResponseCode();
            if(code == 200){
                return changeInputStream(connection.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String changeInputStream(InputStream inputStream) {
        String jsonString = "";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        try{
            while ((len = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
            jsonString = new String(outputStream.toByteArray());
            return jsonString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    public static String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            //url为第三方接口
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            // 发送POST请求必须设置如下两行
            conn = (HttpURLConnection) realUrl.openConnection(); // 打开和URL之间的连接
            // 发送POST请求必须设置如下两行
            conn.setRequestMethod("POST"); // POST方法
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置通用的请求属性(这里的属性要根据第三方系统来设置)
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // 获取URLConnection对象对应的输出流
            out.write(param); // param为发送请求参数
            out.flush(); // flush输出流的缓冲
            in=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));// 定义BufferedReader输入流来读取URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
                System.out.println("OK");
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                } if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    public static String jsonPost(String url_path,JSONObject requestBody) {
        String result = "";
        try {
            URL url = new URL(url_path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection","keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            String json = requestBody.toString();
            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            int responseCode = conn.getResponseCode();
            android.util.Log.e("tag", "responseCode = " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream input = conn.getInputStream();
                StringBuilder sb = new StringBuilder();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb.append((char) ss);
                }
                result = sb.toString();
                android.util.Log.e("tag", "请求结果 = " + sb.toString());
                input.close();
            }
            conn.disconnect();
        } catch (Exception e) {
            android.util.Log.e("tag", "出现异常: " + e.toString());
            e.printStackTrace();
        }
        return result;
    }
    public static String doPostWithParams(String url, Map<String, Object> params) {
        final String NEWLINE = "\r\n";

        HttpURLConnection httpConn = null;
        BufferedInputStream bis = null;
        DataOutputStream dos = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            URL urlObj = new URL(url);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            httpConn.setDoInput(true);
            // 允许传入body参数
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            // POST不支持缓存
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            httpConn.setRequestProperty("Cache-Control", "no-cache");
            httpConn.setRequestProperty("Charset", "utf-8");
            // 这个比较重要，按照上面分析的拼装出Content-Type头的内容 https://blog.csdn.net/weiguang102/article/details/119645861
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.connect();

            dos = new DataOutputStream(httpConn.getOutputStream());
            if (params != null && !params.isEmpty()) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key = entry.getKey();
                    Object value = params.get(key);
                    if(stringBuilder.length() == 0) {
                        stringBuilder.append(key).append("=").append(value == null ? "" : value.toString());
                    } else {
                        stringBuilder.append("&").append(key).append("=").append(value == null ? "" : value.toString());
                    }
                }

                // 这里要个换行
                dos.write((stringBuilder + NEWLINE).getBytes());
                dos.flush();
                dos.close();
            }

            byte[] buffer = new byte[8 * 1024];
            int c = 0;
            if (httpConn.getResponseCode() == 200) {
                bis = new BufferedInputStream(httpConn.getInputStream());
                while ((c = bis.read(buffer)) != -1) {
                    baos.write(buffer, 0, c);
                    baos.flush();
                }
            }
            // 将输入流转成字节数组，返回给客户端。
            return baos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null)
                    dos.close();
                if (bis != null)
                    bis.close();
                baos.close();
                if(httpConn != null) {
                    httpConn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String md5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] md5 = md.digest(data.getBytes(StandardCharsets.UTF_8));

            // 将处理后的字节转成 16 进制，得到最终 32 个字符
            StringBuilder sb = new StringBuilder();
            for (byte b : md5) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}